<script setup lang="ts">
import { h, ref } from "vue";
import type { TableColumns } from "@pureadmin/table";
import { PureTableBar } from "@/components/RePureTableBar";
import { getDeviceList, deviceDelete, deviceSave, deviceSort } from "@/api";
import { message } from "@/utils/message";
import { useTable } from "@/hook/useTable";
import { addDialog } from "@/components/ReDialog";
import { clone } from "@pureadmin/utils";
import ReForm from "./form.vue";
import ReSortForm from "./sortForm.vue";
defineOptions({
  name: "deviceList"
});
/**
 * 搜索
 */
const loading = ref(false);
const formRef = ref();
const formSearch = ref({
  deviceId: null,
  status: null,
  type: null,
  gameCode: null
});
async function onSearch() {
  if (loading.value) return;
  loading.value = true;
  await getInfo();
}
function resetForm() {
  formRef.value.resetFields();
  onSearch();
}
/**
 * table
 */
const { headerCellStyle, pagination, gameV2Options, getSelectV2Games } =
  useTable();
const columns: Array<TableColumns> = [
  { type: "selection", align: "right" },
  { type: "index", label: "序号", width: 80, align: "center", fixed: true },
  { prop: "deviceId", label: "设备ID" },
  { prop: "gameName", label: "接单游戏" },
  { prop: "typeName", label: "设备类型" },
  { prop: "statusName", label: "设备状态" },
  { prop: "weight", label: "设备权重" },
  { prop: "createTime", label: "创建时间" },
  { slot: "operation", label: "操作", fixed: "right" }
];
const tableData = ref([]);
async function getInfo() {
  try {
    const par = {
      ...formSearch.value,
      current: pagination.currentPage,
      size: pagination.pageSize,
      order: "DESC",
      sort: "create_time"
    };
    const res = await getDeviceList(par);
    loading.value = false;
    if (!res.success) {
      message(res.info, { type: "error" });
      return;
    }
    pagination.total = Number(res.data.total);
    tableData.value = res.data.records;
  } finally {
    loading.value = false;
  }
}
/**
 * 分页
 */
async function onCurrentChange(val) {
  pagination.currentPage = val;
  await getInfo();
}
async function onSizeChange(val) {
  pagination.currentPage = 1;
  pagination.pageSize = val;
  await getInfo();
}
/**
 * 列表多选
 */
const multipleSelection = ref([]);
function onSelectionChange(val) {
  console.log("🚀 ~ onSelectionChange ~ val:", val);
  multipleSelection.value = val;
}
const reSortFormRef = ref();
async function onSort() {
  addDialog({
    title: "批量排序",
    closeOnClickModal: false,
    sureBtnLoading: true,
    contentRenderer: () => h(ReSortForm, { ref: reSortFormRef, item: null }),
    beforeSure: (done, { closeLoading }) => {
      const FormRef = reSortFormRef.value.getRef();
      const FormData = reSortFormRef.value.getFormData();
      function chores() {
        FormRef.resetFields();
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      }
      FormRef.validate(async valid => {
        if (valid) {
          try {
            const par = {
              deviceIdList: multipleSelection.value.map(item => item.deviceId),
              weight: Number(FormData.weight)
            };
            const res = await deviceSort(par);
            if (!res.success) {
              closeLoading();
              message(res.info, { type: "error" });
              return;
            }
            message("操作成功", { type: "success" });
            chores();
          } catch (err) {
            closeLoading();
          }
        } else {
          closeLoading();
        }
      });
    }
  });
}
/**
 * 操作按钮相关
 */
const reFormRef = ref();
function onEdit(item) {
  addDialog({
    title: item?.deviceId ? "编辑" : "新增",
    props: {
      item: item?.deviceId ? clone(item) : {}
    },
    closeOnClickModal: false,
    sureBtnLoading: true,
    contentRenderer: () => h(ReForm, { ref: reFormRef, item: null }),
    beforeSure: (done, { closeLoading }) => {
      const FormRef = reFormRef.value.getRef();
      const FormData = reFormRef.value.getFormData();
      function chores() {
        FormRef.resetFields();
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      }
      FormRef.validate(async valid => {
        if (valid) {
          try {
            const par = {
              deviceId: FormData.deviceId,
              type: FormData.type,
              gameCode: FormData.gameCode,
              deviceOs: FormData.deviceOs,
              weight: Number(FormData.weight)
            };
            const res = await deviceSave(par);
            if (!res.success) {
              closeLoading();
              message(res.info, { type: "error" });
              return;
            }
            message("操作成功", { type: "success" });
            chores();
          } catch (err) {
            closeLoading();
          }
        } else {
          closeLoading();
        }
      });
    }
  });
}
async function onDelete(item) {
  try {
    loading.value = true;
    const par = {
      deviceId: item.deviceId
    };
    const res = await deviceDelete(par);
    loading.value = false;
    if (!res.success) {
      message(res.info, { type: "error" });
      return;
    }
    message("操作成功", { type: "success" });
    await onSearch();
  } catch (err) {
    loading.value = false;
  }
}
/**
 * created
 */
async function onLoad() {
  await Promise.all([getInfo(), getSelectV2Games()]);
}
onLoad();
</script>

<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="formSearch"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item label="选择游戏" prop="gameCode">
        <el-select
          v-model="formSearch.gameCode"
          placeholder="请选择游戏"
          class="!w-[250px]"
          clearable
          filterable
        >
          <el-option
            v-for="item in gameV2Options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备ID" prop="deviceId">
        <el-input
          v-model="formSearch.deviceId"
          clearable
          class="!w-[180px]"
          placeholder="请输入设备ID"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-select
          v-model="formSearch.status"
          placeholder="请选择设备状态"
          clearable
          class="!w-[180px]"
        >
          <el-option label="空闲" value="FREE" />
          <el-option label="繁忙" value="BUSY" />
          <el-option label="离线" value="OFFLINE" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="type">
        <el-select
          v-model="formSearch.type"
          placeholder="请选择设备类型"
          clearable
          class="!w-[180px]"
        >
          <el-option label="截图设备" value="SHOT" />
          <el-option label="图片处理设备" value="IMAGE" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch"> 搜索 </el-button>
        <el-button @click="resetForm"> 重置 </el-button>
      </el-form-item>
    </el-form>
    <div class="table-data">
      <PureTableBar title="设备管理" :columns="columns" @refresh="onSearch">
        <template #buttons>
          <el-tooltip
            content="请先选择设备"
            placement="top"
            :disabled="multipleSelection.length > 1"
          >
            <div>
              <el-button
                type="primary"
                class="dl-button"
                :disabled="!multipleSelection.length"
                @click="onSort"
              >
                排序
              </el-button>
            </div>
          </el-tooltip>
        </template>
        <template v-slot="{ size, dynamicColumns }">
          <pure-table
            alignWhole="center"
            :loading="loading"
            :size="size"
            :data="tableData"
            :columns="dynamicColumns"
            :header-cell-style="headerCellStyle"
            :pagination="pagination"
            hide-on-single-page
            @page-size-change="onSizeChange"
            @page-current-change="onCurrentChange"
            @selection-change="onSelectionChange"
          >
            <template #operation="{ row }">
              <el-button text type="primary" @click="onEdit(row)">
                编辑
              </el-button>
              <el-popconfirm
                title="确定要删除该数据？"
                width="200px"
                :hide-after="0"
                placement="top"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="onDelete(row)"
              >
                <template #reference>
                  <el-button text type="primary">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </pure-table>
        </template>
      </PureTableBar>
    </div>
  </div>
</template>
